package com.cskaoyan.gateway.controller.user;


import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.IRegisterService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class RegisterController {
    @Reference(check = false)
    IKaptchaService iKaptchaService;

    @Reference(check = false)
    IRegisterService iRegisterService;

    @Reference(check = false)
    ILoginService iLoginService;

    @Anoymous
    @PostMapping("/register")
    public ResponseData register(@RequestBody Map<String,String> map, HttpServletRequest request)
    {
//        1. 验证传过来的验证码
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");
        String email = map.get("email");

        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kresponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if(!kresponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()))
        {
            return new ResponseUtil<>().setErrorMsg(kresponse.getMsg());
        }

//       2. 插入数据库
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest();
        userRegisterRequest.setEmail(email);
        userRegisterRequest.setUserName(userName);
        userRegisterRequest.setUserPwd(userPwd);
        UserRegisterResponse registersp = iRegisterService.register(userRegisterRequest);
        if(registersp.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()))
        {
            return new ResponseUtil<>().setData(null);
        }
        return new ResponseUtil<>().setErrorMsg(kresponse.getMsg());
    }

    //请求登录
    @Anoymous
    @PostMapping("/login")
    public ResponseData login(@RequestBody Map<String,String> map, HttpServletRequest request,HttpServletResponse response)
    {
////        1. 验证传过来的验证码
        String userName = map.get("userName");
        String userPwd = map.get("userPwd");
        String captcha = map.get("captcha");

        KaptchaCodeRequest kaptchaCodeRequest = new KaptchaCodeRequest();
        String uuid = CookieUtil.getCookieValue(request, "kaptcha_uuid");
        kaptchaCodeRequest.setUuid(uuid);
        kaptchaCodeRequest.setCode(captcha);
        KaptchaCodeResponse kresponse = iKaptchaService.validateKaptchaCode(kaptchaCodeRequest);
        if(!kresponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()))
        {
            return new ResponseUtil<>().setErrorMsg(kresponse.getMsg());
        }
        //2.验证用户名密码
        UserLoginRequest userLoginRequest = new UserLoginRequest();
        userLoginRequest.setUserName(userName);
        userLoginRequest.setPassword(userPwd);
        UserLoginResponse login = iLoginService.login(userLoginRequest);
        if(!login.getCode().equals(SysRetCodeConstants.SUCCESS.getCode()))
        {
            return new ResponseUtil<>().setErrorMsg(login.getMsg());
        }
        //设置token
        Cookie cookie=CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN,login.getToken(),"/",60);
        cookie.setHttpOnly(true);
        response.addCookie(cookie);

//        String info = JwtTokenUtils.builder().token(token).build().freeJwt();
        return new ResponseUtil<>().setData(login);
    }


    //验证登录
    @Anoymous
    @GetMapping("login")
    public ResponseData getlogin(HttpServletRequest request,HttpServletResponse response){
        String token = CookieUtil.getCookieValue(request, TokenIntercepter.ACCESS_TOKEN);
        if(token==null)
        {
            return new ResponseUtil<>().setErrorMsg("token已失效");
        }
        String tokenInfo = iLoginService.getTokenInfo(token);
        String[] splits = tokenInfo.split(",");
        Map<String, String> map = new HashMap<>();
        map.put("username",splits[0]);
        map.put("uid",splits[1]);
        return new ResponseUtil<>().setData(map);
    }


    /**
     * 用户登出
     * @param request
     * @param response
     * @return
     */
    @GetMapping("loginOut")
    public ResponseData loginOut(HttpServletRequest request, HttpServletResponse response){
        Cookie[] cookies = request.getCookies();
        if(cookies != null){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(TokenIntercepter.ACCESS_TOKEN)){
                    cookie.setValue(null);
                    cookie.setMaxAge(0);
                    cookie.setPath("/");
                    response.addCookie(cookie);
                }
            }
        }
        return new ResponseUtil().setData(null);
    }
}
